//
//  CustomNumbleKeyboardView.m
//  CustomNumbleKeyboard
//
//  Created by wi on 12-3-19.
//  Copyright (c) 2012年 lizhiwei All rights reserved.
//

#import "CustomNumbleKeyboardView.h"

#define kButtonSizeWidth 88.0f
#define kButtonSizeHeight 50.0f

@implementation CustomNumbleKeyboardView

@synthesize delegate = _delegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self customView:frame];
    }
    return self;
}

- (void)customView:(CGRect)frame
{
    // set the frame
    self.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 238.0f);
    
    // set the background image
    UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:
                                        CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height)];
    [backgroundImageView setImage:[UIImage imageNamed:@"number_keyboard_background"]];
    [self addSubview:backgroundImageView];
    
    // add the button
    for (int x = 0; x < 12; x++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(24.0f + x%3*(kButtonSizeWidth + 4.0f), 15.0f + x/3*(kButtonSizeHeight + 5.0f), 
                                 88.0f, 50.0f)];
        if (x <= 9) 
        {
            [btn setTag:(x + 1)];
        }
        else if (x == 11)
        {
            btn.tag = x;
        }
        else if (x == 10)
        {
            btn.tag = 0;
        }
        else
        {
            // btn.tag = x;
        }
 
        [btn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"number_%d_select",btn.tag]] forState:UIControlStateHighlighted];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"number_%d_select",btn.tag]] forState:UIControlStateSelected];
        btn.adjustsImageWhenHighlighted = TRUE;
        [btn addTarget:self action:@selector(numbleButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
    }
}

- (void)numbleButtonClicked:(id)sender
{
    UIButton* btn = (UIButton*)sender;
    
    NSInteger number = btn.tag;
    

    
    // no delegate, print log info
    if (nil == _delegate) 
    {
        NSLog(@"button tag [%d]",number);
        return;
    }
    
    if (number <= 9 && number >= 0) 
    {
        [_delegate numberKeyBoardInput:number];
        return;
    }
    
    if (10 == number) 
    {
        [_delegate numberKeyBoardBackspace];
        return;
    }
    
    if (11 == number) 
    {
        [_delegate numberKeyBoardFinish];
        return;
    }
}

@end
